const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TicketSchema = new Schema({
  'name': {
    type: String,
    default: 'ticket'
  },
  'ticket': {
    type: String,
    required: true,
    trim: true
  },
  expires_in: {
    type: Number,
    required: true
  },
  meta: {
    createdAt: {
      type: Number,
      default: new Date().valueOf()
    },
    updatedAt: {
      type: Number,
      default: new Date().valueOf()
    }
  }
});
TicketSchema.pre('save', function (next) {
  // do stuff
  if (this.isNew) {
    this.meta.createdAt = this.meta.updatedAt = new Date().valueOf()
  } else {
    this.meta.updatedAt = new Date().valueOf()
  }
  next();
});
TicketSchema.statics = {
  async getTicket() {
    const ticket = await this.findOne({
      name: 'ticket'
    })
    if (ticket && ticket.ticket) {
      ticket.ticket = ticket.ticket
      ticket.expires_in = ticket.expires_in
    }

    return ticket;
  },
  async saveTicket(data) {
    let ticket = await this.findOne({
      name: 'ticket'
    })
    if (!ticket) {
      ticket = new Ticket({
        'name': 'ticket',
        'ticket': data['ticket'],
        'expires_in': data['expires_in']
      })
    } else {
      ticket['expires_in'] = data['expires_in'];
      ticket.ticket = data['ticket'];
    }
    await ticket.save()
    return data;
  }
}

const Ticket = mongoose.model('Ticket', TicketSchema, 'ticket');
